package com.dc.event.config.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Node;
import org.pentaho.di.job.JobEntryListener;

import com.dc.di.xml.XmlTool;
import com.dc.event.Const;
import com.dc.event.config.ConfigFactory;
import com.dc.event.config.ListenerConfig;
import com.dc.event.listener.SipJobListener;


public class DefaultConfigFactory implements ConfigFactory {
	protected XmlTool xmlTool;
	
	public DefaultConfigFactory(String path){
		try {
			this.xmlTool = new XmlTool(path);
		} catch (Exception e) {
			throw new RuntimeException("init DefaultJobConfigFactory has error:",e);
		}		
	}
	@SuppressWarnings("unchecked")
	@Override
	public List<ListenerConfig<JobEntryListener>> createJobEntryListenerConfigs() throws Exception{
		List<Node> nodeList = xmlTool.getNodes(Const.JOBENTRYCONFIG_PATH);
		List<ListenerConfig<JobEntryListener>> configList = new ArrayList<ListenerConfig<JobEntryListener>>(nodeList.size());
		for (Node node : nodeList) {
			String className =  xmlTool.getTextFromNode(node,"class");
			Class<JobEntryListener> clazz = (Class<JobEntryListener>) Class.forName(className);
			ListenerConfig jobEntryListenerConfig = new DefaultListenerConfig<JobEntryListener>(clazz,getParamsMap(node));
			configList.add(jobEntryListenerConfig);
		};
		return configList;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<ListenerConfig<SipJobListener>> createJobListenerConfigs() throws Exception{
		List<Node> nodeList = xmlTool.getNodes(Const.JOBCONFIG_PATH);
		List<ListenerConfig<SipJobListener>> configList = new ArrayList<ListenerConfig<SipJobListener>>(nodeList.size());
		for (Node node : nodeList) {
			String className =  xmlTool.getTextFromNode(node,"class");
			Class<SipJobListener> clazz = (Class<SipJobListener>) Class.forName(className);
			ListenerConfig jobListenerConfig = new DefaultListenerConfig<SipJobListener>(clazz,getParamsMap(node));
			configList.add(jobListenerConfig);
		};
		return configList;
	}
	
	public Map<String, String> getParamsMap(Node node){
		Map<String, String> map = new HashMap<String, String>();
		List<Node> list = xmlTool.getNodes(node, "init-param");
		for (Node node2 : list) {
			map.put(xmlTool.getTextFromNode(node2, "param-name"),xmlTool.getTextFromNode(node2, "param-value"));
		}
		return map;
	} 

}
